package com.openswimsoftware.orm.model.list.query;

import com.openswimsoftware.orm.ORM;
import com.openswimsoftware.orm.model.Model;
import com.openswimsoftware.orm.model.exception.InvalidModelField;
import com.openswimsoftware.orm.model.list.ModelList;
import com.openswimsoftware.orm.model.query.where.QueryWhere;
import com.openswimsoftware.orm.model.query.where.WhereCombo;
import com.openswimsoftware.orm.model.query.where.WhereOperator;

import android.content.Context;
import android.util.Log;

public class ModelListDelete<E extends  Model<E>> extends ModelListQuery<E, ModelListDelete<E>> {
	
	public ModelListDelete(Context context, Class<E> modelType, ModelList<E> models)
	{
		super(context, modelType, models);
	}
	
	public ModelListDelete<E> where(String field, WhereOperator operator, String value) throws InvalidModelField
	{
		this.where(WhereCombo.AND, field, operator, value);
		
		return this;
	}
	
	public ModelListDelete<E> where(WhereCombo combo, String field, WhereOperator operator, String value) throws InvalidModelField
	{
		this.whereList.add(new QueryWhere(combo, ORM.getField(this.modelType, field), operator, value));
		
		return this;
	}
	
	public boolean execute()
	{
		this.dbInterface.openDB();
		
		if ((this.models.size() == 0) && (this.models.getParentId() > -1))
		{
			this.models.find();
		}
		
		String table = ORM.tableName(this.modelType);
		String where = QueryWhere.whereString(this.whereList);
		String[] whereArgs = QueryWhere.whereArgs(this.whereList);
		
		Log.d("orm", "Deleting from list ModelList<" + this.modelType.getSimpleName() + ">");
		if (where != null)
		{
			Log.d("orm", "Where: " + where);
			for (String arg: whereArgs)
			{
				Log.d("orm", arg);
			}
		}
		
		int num = this.dbInterface.getDB().delete(table, where, whereArgs);
		
		this.dbInterface.closeDB();
		
		return (num > 0);
	}
	
}
